package sapling.web.admin;

import io.goeasy.GoEasy;
import org.apache.http.util.TextUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import sapling.dao.*;
import sapling.model.*;
import sapling.service.PushService;
import sapling.service.PutOutService;
import sapling.service.StorageService;
import sapling.service.TreeService;

import java.math.BigDecimal;
import java.util.*;

/**
 * Created by ever on 2016/10/9.
 */
@Controller
@RequestMapping(value = "/admin/finance")
public class FinanceAction {
    @Autowired
    TreeDao treeDao;
    @Autowired
    BatchDao batchDao;
    @Autowired
    OutboundOrderDao outboundOrderDao;
    @Autowired
    MarkorderDao markorderDao;
    @Autowired
    TreeWellDao treeWellDao;
    @Autowired
    TreeService treeService;
    @Autowired
    CostDao costDao;
    @Autowired
    PutOutService putOutService;
    @Autowired
    LandMassDao landMassDao;
    @Autowired
    UpdateorderDao updateorderDao;
    @Autowired
    StorageService storageService;
    @Autowired
    private PushService pushService;
    @Autowired
    private AdminDao adminDao;

    @RequestMapping("/batch")
    public String list(Model model) {
        List<Batch> batches=new ArrayList<>();
        for (Batch bar:batchDao.findHavebatch()) {
            List<Tree> treeList=treeDao.findCount(bar.getBatch_id());
           /* if(Objects.nonNull(treeList)&&treeList.size()>0){
                Tree tree= treeList.get(0);
                LandMass landMass= landMassDao.findOne(tree.getLandmassid());
                if(Objects.nonNull(landMass)){
                    bar.setLandmass(landMass.getAreaLocation().getSerialNumber()+landMass.getSerialNumber());
                    bar.setNumber(treeList.size());
                    batches.add(bar);
                }
            }*/
            String land="";
            Set<String> set=new HashSet<>();
            for (Tree tree:treeList) {
                LandMass landMass= landMassDao.findOne(tree.getLandmassid());
                if(Objects.nonNull(landMass)){
                    set.add(landMass.getAreaLocation().getSerialNumber()+landMass.getSerialNumber());
                }
            }
            for (String str:set) {
                if(str!=null&&str.length()>1){
                    land+=str+";";
                }
            }
            if(land!=null&&land.length()>1){
                bar.setLandmass(land);
                bar.setNumber(treeList.size());
                batches.add(bar);
            }
        }
        model.addAttribute("batchlist1",batches);
        model.addAttribute("batchlist2",batchDao.findNullbatch());
        return "admin/finance/batch";
    }


    @RequestMapping("/put")
    public String put(Model model) {
        model.addAttribute("trees",putOutService.put());
        return "admin/finance/put";
    }

    @RequestMapping("/out")
    public String out(Model model) {
        List<OutboundOrder> outStatus = outboundOrderDao.findByStatus(0);
        List<Tree> treeList=new ArrayList<>();
        for(OutboundOrder out:outStatus){
            if(Objects.nonNull(out.getTrees())&&out.getTrees().size()>0){
                Tree tree = out.getTrees().get(0);
                tree.setTree_id(out.getOutboundOrder_id());
                int number=0;
                for (Tree value:out.getTrees()) {
                    if(Tree.TYPE_TREE_AWAIT_OUT==value.getSalesState()){
                        number++;
                    }
                }
                tree.setNumber(number);
                if(Objects.nonNull(out.getTransactionAmount())){
                    tree.setPrice(out.getTransactionAmount().doubleValue());
                }else {
                    tree.setPrice(0);
                }
                tree.setCreatetime(out.getGmt_payment());
                tree.setUsername(out.getName());
                if(number>0){
                    treeList.add(tree);
                }
            }
        }
        model.addAttribute("trees",treeList);

        List<OutboundOrder> outStatus1 = outboundOrderDao.findByStatus(1);
        List<Tree> treeList2=new ArrayList<>();
        for(OutboundOrder out:outStatus1){
            if(Objects.nonNull(out.getTrees())&&out.getTrees().size()>0){
                Tree tree = out.getTrees().get(0);
                tree.setTree_id(out.getOutboundOrder_id());
                int number2=0;
                for (Tree value:out.getTrees()) {
                    if(Tree.TYPE_TREE_OUT==value.getSalesState()){
                        number2++;
                    }
                }
                tree.setNumber(number2);
                if(Objects.nonNull(out.getTransactionAmount())){
                    tree.setPrice(out.getTransactionAmount().doubleValue());
                }else {
                    tree.setPrice(0);
                }
                tree.setCreatetime(out.getGmt_payment());
                tree.setUsername(out.getName());
                if(number2>0){
                    treeList2.add(tree);
                }
            }
        }
        model.addAttribute("trees1",treeList2);
        return "admin/finance/out";
    }

    @RequestMapping("/die")
    public String die(Model model){
        List<Markorder> markorderlist5 = markorderDao.findBySalestate(5);
        List<Tree> trees5=new ArrayList<>();
        for(Markorder mark:markorderlist5){
            if(Objects.nonNull(mark.getTreesList())&&mark.getTreesList().size()>0){
                Tree tree = mark.getTreesList().get(0);
                tree.setTree_id(mark.getMarkorder_id());
                int number=0;
                for (Tree value:mark.getTreesList()) {
                    if(Tree.TYPE_TREE_AWAIT_DIE==value.getSalesState()){
                        number++;
                    }
                }
                LandMass landMass=landMassDao.findOne(tree.getLandmassid());
                if(Objects.nonNull(landMass)){
                    tree.setSerialNumber(landMass.getAreaLocation().getSerialNumber()+landMass.getSerialNumber());
                }
                tree.setNumber(number);
                tree.setCreatetime(mark.getCreatetime());
                tree.setUsername(mark.getName());
                if(number>0){
                    trees5.add(tree);
                }
            }
        }
        model.addAttribute("trees5",trees5);

        List<Markorder> markorderlis4 = markorderDao.findBySalestate(4);
        List<Tree> trees4=new ArrayList<>();
        for(Markorder mark:markorderlis4){
            if(Objects.nonNull(mark.getTreesList())&&mark.getTreesList().size()>0){
                Tree tree = mark.getTreesList().get(0);
                tree.setTree_id(mark.getMarkorder_id());
                int number=0;
                for (Tree value:mark.getTreesList()) {
                    if(Tree.TYPE_TREE_DIE==value.getSalesState()){
                        number++;
                    }
                }
                tree.setNumber(number);
                tree.setCreatetime(mark.getCreatetime());
                tree.setUsername(mark.getName());
                if(number>0){
                    trees4.add(tree);
                }
            }
        }
        model.addAttribute("trees4",trees4);
        return "admin/finance/die";
    }

    @RequestMapping("/die/recover")
    public String recover(Long tree_id){
        if(Objects.nonNull(tree_id)){
            Markorder markorder=markorderDao.findOne(tree_id);
            for (Tree t:markorder.getTreesList()) {
                t.setResponseState(0);
                t.setMarkorder(null);
                treeDao.save(t);
            }
        }
        return "redirect:/admin/finance/die";
    }

    @RequestMapping("/die/confirm")
    @ResponseBody
    public void dieConfirm(String treeids,double price){
        if(!TextUtils.isEmpty(treeids)) {
            String res = treeids.substring(0, treeids.length() - 1);
            for(String treeid:res.split(";")){
                long id = Long.parseLong(treeid);
                treeService.dieConfirm(Tree.TYPE_TREE_DIE,id);
            }
            Cost cost1=new Cost();
            cost1.setName("死苗计入");
            cost1.setRests(price);
            cost1.setEnteringTime(new Date());
            costDao.save(cost1);
        }

        for (Batch batch:batchDao.findHavebatch()) {
            List<Tree> treeList=treeDao.findBatchsatate(batch.getBatch_id(),Tree.TYPE_TREE_DIE);
            if(Objects.nonNull(batch.getTrees())&&batch.getTrees().size()>0){
                if(Objects.nonNull(treeList)&&treeList.size()>0){
                    batch.setDienumber(treeList.size());
                }
                batch.setNumber(batch.getTrees().size());
                int avg=treeList.size()/batch.getTrees().size();
                batch.setDeathrate(avg);
                if(avg*100>=batch.getDeathrate()){
                    pushService.informDie("finance",batch.getBatchNumber()+"批次的苗木死亡数量已达到设定值，请及时处理");
                    for (Admin admin:adminDao.findAll()) {
                        for (Role value:admin.getRoleList() ) {
                            if(value.getName().equals("admin")||value.getName().equals("finance")){
                                GoEasy goEasy = new GoEasy("BC-a5c00f8af086408888488e852b557b81");
                                goEasy.publish(admin.getUsername(),batch.getBatchNumber()+"批次的苗木死亡数量已达到设定值，请及时处理");
                            }
                        }
                    }
                }
            }
        }
    }

    @RequestMapping("/out/warehouse")
    @ResponseBody
    public void outwarehouse(String treeids,BigDecimal price,String location){
        if(!TextUtils.isEmpty(treeids)) {
            String res = treeids.substring(0, treeids.length() - 1);
            for(String treeid:res.split(";")){
                long id = Long.parseLong(treeid);
                treeService.outwarehouse(Tree.TYPE_TREE_OUT,id,price,location);
            }
        }
    }

    @RequestMapping("/mark")
    public String mark(Model model){
        List<Markorder> markorders= markorderDao.findBySalestate(3);
        List<Tree> trees=new ArrayList<>();
        for(Markorder mark:markorders){
            if(Objects.nonNull(mark.getTreesList())&&mark.getTreesList().size()>0){
                Tree tree = mark.getTreesList().get(0);
                tree.setTree_id(mark.getMarkorder_id());
                int number=0;
                for (Tree value:mark.getTreesList()) {
                    if(Tree.TYPE_TREE_SIGN==value.getSalesState()){
                        number++;
                    }
                }
                LandMass landMass=landMassDao.findOne(tree.getLandmassid());
                String serialNumber="";
                if(Objects.nonNull(landMass)){
                    serialNumber=landMass.getAreaLocation().getSerialNumber()+landMass.getSerialNumber();
                }
                tree.setSerialNumber(serialNumber);
                tree.setNumber(number);
                tree.setCreatetime(mark.getCreatetime());
                tree.setUsername(mark.getName());

                BigDecimal bg = new BigDecimal(number*tree.getPrice());
                double f1 = bg.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
                tree.setTotalprice(f1);
                if(number>0){
                   trees.add(tree);
               }
            }
        }
        model.addAttribute("trees",trees);
        return "admin/finance/costing";
    }


    @RequestMapping("/mark/one")
    @ResponseBody
    public List<Tree> markone(Long id){
        Markorder markorders= markorderDao.findOne(id);
        List<Tree> trees=new ArrayList<>();
        for (Tree value:markorders.getTreesList()) {
            if(Tree.TYPE_TREE_SIGN==value.getSalesState()){
                Tree tree=new Tree();
                tree.setTree_id(value.getTree_id());
                LandMass landMass=landMassDao.findOne(value.getLandmassid());
                String serialNumber="";
                TreeWell treeWell=treeWellDao.findOne(value.getTree_well_id());
                if(Objects.nonNull(landMass)&&Objects.nonNull(treeWell)){
                    serialNumber=landMass.getAreaLocation().getSerialNumber()+landMass.getSerialNumber()+"-"+treeWell.getSerialNumber();
                }
                tree.setRemark(value.getRemark());
                tree.setTreeSpecies(value.getTreeSpecies());
                tree.setSerialNumber(serialNumber);
                tree.setCreatetime(markorders.getCreatetime());
                tree.setUsername(markorders.getName());
                BigDecimal bg = new BigDecimal(value.getPrice());
                double f1 = bg.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
                tree.setTotalprice(f1);
                trees.add(tree);
            }
        }
        return trees;
    }

    @RequestMapping("/deblocking")
    public String deblocking(Long tree_id){
        if(Objects.nonNull(tree_id)){
            Markorder markorder=markorderDao.findOne(tree_id);
            List<Tree> trees=markorder.getTreesList();
            for (Tree value:trees) {
                value.setSalesState(Tree.TYPE_TREE_AWAIT_SELL);
                treeDao.save(value);
            }
            markorder.setSalestate(Tree.TYPE_TREE_AWAIT_SELL);
            markorderDao.save(markorder);
        }
        return "redirect:/admin/finance/mark";
    }

    @RequestMapping("/deblocking/one")
    public String deblockone(Long tree_id){
        if(Objects.nonNull(tree_id)){
            Tree tree=treeDao.findOne(tree_id);
            if(Objects.nonNull(tree)){
                tree.setSalesState(Tree.TYPE_TREE_AWAIT_SELL);
                treeDao.save(tree);
            }
        }
        return "redirect:/admin/finance/mark";
    }

    @RequestMapping("/cost")
    public String cost(Model model){
        model.addAttribute("cost",costDao.findByEnteringTimeDesc());
        return "admin/finance/cost";
    }


    @RequestMapping("/datecost")
    public String datecost(String date,Model model){
       if(Objects.nonNull(date)&&date.length()>0){
           String str[]= date.split(" - ");
           if(str.length==2){
               model.addAttribute("cost",costDao.findByDate(str[0],str[1]));
           }
       }else {
           model.addAttribute("cost",costDao.findByEnteringTimeDesc());
       }
        return "admin/finance/cost";
    }

    @RequestMapping("/cost/input")
    public String costInput(){
        return "admin/finance/cost_input";
    }

    @RequestMapping("/save/cost")
    public String saveCost(Cost cost){
        Cost cost1=new Cost();
        if(Objects.nonNull(cost.getCost_id())){
            cost1=costDao.findOne(cost.getCost_id());
        }
        cost1.setWaterrate(cost.getWaterrate());
        cost1.setPersonrate(cost.getPersonrate());
        cost1.setLandrent(cost.getLandrent());
        cost1.setMedicine(cost.getMedicine());
        cost1.setChemical(cost.getChemical());
        cost1.setEnteringTime(new Date());
        costDao.save(cost1);
        return "redirect:/admin/finance/cost";
    }

    @RequestMapping("/update")
    public String update(Model model){
        model.addAttribute("update",updateorderDao.findAll());
        return "admin/finance/update";
    }

    @RequestMapping("/update/confirm")
    public String confirm(Long updateorder_id,String cost){
        double costs=0;
        if(cost!=null&&cost.length()>0){
            costs=Double.parseDouble(cost);
        }
        storageService.confirmUpdate(updateorder_id,costs);
        return "redirect:/admin/finance/update";
    }

    @RequestMapping("/setting")
    public String setting(Model model){
        List<Batch> batches=new ArrayList<>();
        for (Batch batch:batchDao.findHavebatch()) {
            List<Tree> treeList=treeDao.findBatchsatate(batch.getBatch_id(),Tree.TYPE_TREE_DIE);
            if(Objects.nonNull(batch.getTrees())&&batch.getTrees().size()>0){
                if(Objects.nonNull(treeList)&&treeList.size()>0){
                   batch.setDienumber(treeList.size());
                }
                batch.setNumber(batch.getTrees().size());
            }
            batches.add(batch);
        }
        model.addAttribute("batchlist1",batches);
        return "admin/finance/bset";
    }


}
